package com.neteast.androidclient.newscenter.service;

import com.neteast.androidclient.newscenter.Global;
import com.neteast.androidclient.newscenter.NewsCenter;
import com.neteast.androidclient.newscenter.client.NewsCenterClient;
import com.neteast.androidclient.newscenter.util.ConfigUtil;
import com.neteast.androidclient.newscenter.util.DeBugUtil;
import com.neteast.androidclient.newscenter.util.LoginUtil;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class NetService extends Service{

	private NewsCenterClient client;
	private WakeLock wakeLock;
	private NewsCenter newsCenter;
	private Thread netThread;
	
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		newsCenter = (NewsCenter) getApplication();
		client=new NewsCenterClient(NetService.this);
		tryConnectNet();
		acquireWakeLock();
	}

	private void acquireWakeLock() {      
		if (wakeLock == null) {
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getCanonicalName());
			wakeLock.acquire();
		}
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent!=null) {
			final String state = intent.getStringExtra(Global.INTENT_EXTRA_LOGIN_STATE);
			Log.i("test", "state>>>>>>>>>"+state);
			if (!TextUtils.isEmpty(state)&&client!=null) {
				new Thread(new Runnable() {
					@Override
					public void run() {
						if (state.equals(Global.LOGIN)) {
							client.changeUser(LoginUtil.getUserId(getApplicationContext()));
						} else {
							client.changeUser(0);
						}
					}
				}).start();
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}
	void tryConnectNet(){
		ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
		NetworkInfo info = cm.getActiveNetworkInfo(); 
		if (info!= null && info.isAvailable()){
			startNetThread();
			//Toast.makeText(this, "网络已经连接", Toast.LENGTH_SHORT).show();
		}else {
			Toast.makeText(this, "没有连接到网络，请设置wifi", Toast.LENGTH_SHORT).show();
			stopSelf();
		} 
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		releaseWakeLock();
		if (client!=null) {
			client.release();
		}
		if (netThread!=null&&netThread.isAlive()) {
			netThread.interrupt();
		}
	}
	private void releaseWakeLock() {
		if (wakeLock != null && wakeLock.isHeld()) {
			wakeLock.release();
			wakeLock = null;
		}
	}
	
	private void startNetThread() {
		netThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					client.initClient();
					client.setTimeOut(60000);
					client.connectServer(ConfigUtil.getBootStrapIp(getApplicationContext()), 
							ConfigUtil.getBootStrapPort(getApplicationContext()));
					client.startListen();
					client.requestBootStrap();
				} catch (Exception e) {
					Log.i("test", e.getMessage(),e);
					DeBugUtil.printException(getApplicationContext(), e);
				}
			}
		});
		netThread.start();
	}
	
	public void restart(){
		Context context = getApplicationContext();
		stopSelf();
		context.startService(new Intent(context, NetService.class));
	}
	
	public void notifyHasNews() {
		if (newsCenter.mainActivity!=null) {
			newsCenter.mainActivity.notifyNewsNum();
		}
	}
}
